package ferus.tigris.lines;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import ferus.tigris.lines.Builders.AbstractBehaviorBuilder;
import ferus.tigris.lines.personages.AbstractBehavior;

import android.graphics.Point;

public class Matrix {
	private int columns = 6;
	private int rows = 6;
	private Vector< Vector<AbstractBehavior> > marks;
	
	public Matrix() {
		init(columns, rows);
	}
	
	public Matrix(int columns, int rows) {
		init(columns, rows);
	}
	void init(int columns, int rows) {
		this.columns = columns;  
		this.rows = rows;
		marks = new Vector< Vector<AbstractBehavior> >();
		marks.setSize(columns);
		for(int i = 0; i < columns; i++) {
			Vector<AbstractBehavior> column = new Vector<AbstractBehavior>();
			column.setSize(rows);
			marks.setElementAt(column, i);
		}
		
		AbstractBehaviorBuilder builder = new AbstractBehaviorBuilder();
		for(int x = 0; x < columns(); x++) {
			for(int y = 0; y < rows(); y++) {
				AbstractBehavior mark = builder.createNull();
				insertMark(x, y, mark);
			}
		}
	}

	public List<AbstractBehavior> getMarks() {
		List<AbstractBehavior> list = new ArrayList<AbstractBehavior>();
		for(int y = rows - 1; y >= 0; y--)
			for(int x = 0; x < columns; x++)
				list.add(getMark(x, y));
		return list;
	}

	public AbstractBehavior getMark(int x, int y) {
		AbstractBehavior mark = marks.elementAt(x).elementAt(y);
		return mark;
	}

	public void insertMark(int x, int y, AbstractBehavior mark) {
		mark.saveAt(this, new Point(x, y));
		this.marks.elementAt(x).setElementAt(mark, y);
	}
	
	public int columns() {
		return columns;
	}

	public int rows() {
		return rows;
	}

	public boolean valid(int x, int y) {
		if((x < 0)||(x >= columns))return false;
		if((y < 0)||(y >= rows))return false;
		return true;
	}

	public void restoreFrom(Matrix prevState) {
		for(int x = 0; x < columns; x++)
			for(int y = 0; y < rows; y++)
				insertMark(x, y, prevState.getMark(x, y));
	}
}
